<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<jsp:include page="../common/common.jsp">
	<jsp:param name="title" value="用户"/>
</jsp:include>

<div class="page-header">
	<h1>
		${empty user.id ? '添加' : '修改'}用户
	</h1>
</div>

<div class="row">
	<div class="col-xs-12">
		<!-- PAGE CONTENT BEGINS -->
		<form id="_editForm" class="form-horizontal" role="form" 
			validate="true">
			<input type="hidden" name="id" value="${user.id}">
			
			<div class="form-group">
				<label for="_account" class="col-sm-3 control-label no-padding-right"><span class="form-star">*</span>登录名</label>

				<div class="col-sm-9">
					<div class="input-medium help-validate">
						<div class="input-group">
							<input id="_account" name="account" type="text" value="${user.account}" class="form-data"
								ajax="{url : '${_path}/admin/user/validateAccount', dataId : '_editForm'}"
								required="true" minlength = '4' maxlength = '64'/>
							<span class="input-group-addon">
								<i class="ace-icon fa fa-user"></i>
							</span>
						</div>
					</div>
				</div>
				
			</div>
			
			<div class="form-group">
				<label for="_password" class="col-sm-3 control-label no-padding-right">${empty user.id ? '<span class="form-star">*</span>' : ''}密码</label>
				
				<div class="col-sm-9">
					<div class="input-medium help-validate">
						<div class="input-group">
							<input id="_password" name="password" type="password" value="" class="form-data"
								${!empty user.id ? 'data-rel="tooltip" title="不修改请留空"' : ''}
								${empty user.id ? 'required="true"' : ''} minlength = '6' maxlength = '16'/>
							<span class="input-group-addon">
								<i class="ace-icon fa fa-lock"></i>
							</span>
						</div>
					</div>
				</div>
			</div>
			
			<div class="form-group form-group-role">

				<label class="col-sm-3 control-label no-padding-right"><span class="form-star">*</span>角色</label>

				
				<div class="col-xs-12 col-sm-9">
					<div class="clearfix help-validate">

						<c:forEach var="item" items="${roleList}" begin="0" end="0">

							<label> <input name="roleId" type="radio"

								value="${item.id}" class="ace roleCheckbox" 

								${item.isChecked ? 'checked="checked"' : ''} /> <span

								class="lbl">&nbsp;&nbsp;${item.name}</span>

							</label>

						</c:forEach>

						<c:forEach var="item" items="${roleList}" begin="1">

							<label> <input name="roleId" type="radio"

								value="${item.id}" class="ace roleCheckbox" checked="checked" />

								<span class="lbl">&nbsp;&nbsp;${item.name}</span>
							</label>
						</c:forEach>
						<input id="_roleIds" type="hidden" name="roleIds" value="">
					</div>
				</div>
			</div>
			
			<div class="form-group">
				<label class="control-label col-xs-12 col-sm-3 no-padding-right"><span class="form-star">*</span>是否启用</label>

				<div class="col-xs-12 col-sm-9">
					<div class="clearfix help-validate">
						<div>
							<label class="line-height-1 blue">
								<input name="isEnable" value="true" type="radio" class="ace" ${user.isEnable ? 'checked="checked"' : ''}/>
								<span class="lbl"> 是</span>
							</label>
						</div>
	
						<div>
							<label class="line-height-1 blue">
								<input name="isEnable" value="false" type="radio" class="ace" ${!user.isEnable ? 'checked="checked"' : ''}/>
								<span class="lbl"> 否</span>
							</label>
						</div>
					</div>
				</div>
			</div>

			
			<div class="form-group ipRow" id="form-group-ip0">
				<label class="col-sm-3 control-label no-padding-right lableIp">设定ip区间</label>
				
				<div class="col-xs-12 col-sm-9 ipRangeRow">
					
					<c:choose>
						<c:when test="${empty ipLimitList}">
							<div class="clearfix help-validate ipRange">
								<input class="ip startIp" value="" type="text">
								<span>-</span>
								<input class="ip endIp" value="" type="text">
								<i class="ace-icon glyphicon glyphicon-plus" style="cursor: pointer;"></i>
							</div>
						</c:when>
						
						<c:otherwise>
							<c:forEach var="item" items="${ipLimitList}" begin="0" end="0">
								<div class="clearfix help-validate ipRange" style="margin-top:6px;">
								<input class="ip startIp" value="${item.startIp}" type="text">
								<span>-</span>
								<input class="ip endIp" value="${item.endIp}" type="text">
								<i class="ace-icon glyphicon glyphicon-plus" style="cursor: pointer;"></i>
								</div>
							</c:forEach>
							<c:forEach var="item" items="${ipLimitList}" begin="1" >
								<div class="clearfix help-validate ipRange" style="margin-top:6px;">
									<input class="ip startIp" value="${item.startIp}" type="text">
									<span>-</span>
									<input class="ip endIp" value="${item.endIp}" type="text">
									<i class="ace-icon glyphicon glyphicon-remove" style="cursor: pointer;"></i>
								</div>
							</c:forEach>
						</c:otherwise>
					</c:choose>
					
					
				</div>
				
			</div>
			
			<!-- 日期显示开始 add by zwy -->
		
				<div class="form-group form-group-time">
				<label class="col-sm-3 control-label no-padding-right">设置日期时间段</label>
				<div class="col-xs-12 col-sm-9 dateRangeRow">
				
					<c:choose>
						<c:when test="${empty dateLimitList}">
							<div class="clearfix help-validate dateRange">
								 <input class="form-data date-timepicker date-timepicker1" value="" type="text"/>
								<span>-</span>
								<input class="form-data date-timepicker date-timepicker2" value="" type="text"/>
								<i class="ace-icon glyphicon glyphicon-plus" style="cursor: pointer;"></i>
							</div>
						</c:when>
						
						<c:otherwise>
							<c:forEach var="item" items="${dateLimitList}" begin="0" end="0">
								<div class="clearfix help-validate dateRange" style="margin-top:6px;">
									<input class="form-data date-timepicker date-timepicker1"  type="text" value="<fmt:formatDate value='${item.startDatetime}' pattern='yyyy-MM-dd HH:mm' />"/>
									<span>-</span>
									<input class="form-data date-timepicker date-timepicker2" value="<fmt:formatDate value='${item.endDatetime}' pattern='yyyy-MM-dd HH:mm' />" type="text"/>
									<i class="ace-icon glyphicon glyphicon-plus" style="cursor: pointer;"></i>
								</div>
							</c:forEach>
							<c:forEach var="item" items="${dateLimitList}" begin="1" >
								<div class="clearfix help-validate dateRange" style="margin-top:6px;">
									<input class="form-data date-timepicker date-timepicker1"  type="text" value="<fmt:formatDate value='${item.startDatetime}' pattern='yyyy-MM-dd HH:mm' />"/>
									<span>-</span>
									<input class="form-data date-timepicker date-timepicker2" value="<fmt:formatDate value='${item.endDatetime}' pattern='yyyy-MM-dd HH:mm' />" type="text"/>
									<i class="ace-icon glyphicon glyphicon-remove" style="cursor: pointer;"></i>
								</div>
							</c:forEach>
						</c:otherwise>
					</c:choose>
				
				</div>
			</div>
			
			<div class="form-group form-group-everydayTime">
				<label class="col-sm-3 control-label no-padding-right">设置每日循环时间段</label>
				<div class="col-xs-12 col-sm-9 everydayRow">
				
					<c:choose>
						<c:when test="${empty timeLimitList}">
							<div class="clearfix help-validate everydayRange">
								 <input class="form-data timepicker timepicker1" value="" type="text"/>
								<span>-</span>
								<input class="form-data timepicker timepicker2" value="" type="text"/>
								<i class="ace-icon glyphicon glyphicon-plus" style="cursor: pointer;"></i>
							</div>
						</c:when>
						
						<c:otherwise>
							<c:forEach var="item" items="${timeLimitList}" begin="0" end="0">
								<div class="clearfix help-validate everydayRange" style="margin-top:6px;">
									<input class="form-data timepicker timepicker1"  type="text" value="<fmt:formatDate value='${item.startDatetime}' pattern='HH:mm' />"/>
									<span>-</span>
									<input class="form-data timepicker timepicker2" value="<fmt:formatDate value='${item.endDatetime}' pattern='HH:mm' />" type="text"/>
									<i class="ace-icon glyphicon glyphicon-plus" style="cursor: pointer;"></i>
								</div>
							</c:forEach>
							<c:forEach var="item" items="${timeLimitList}" begin="1" >
								<div class="clearfix help-validate everydayRange" style="margin-top:6px;">
									<input class="form-data timepicker timepicker1"  type="text" value="<fmt:formatDate value='${item.startDatetime}' pattern='HH:mm' />"/>
									<span>-</span>
									<input class="form-data timepicker timepicker2" value="<fmt:formatDate value='${item.endDatetime}' pattern='HH:mm' />" type="text"/>
									<i class="ace-icon glyphicon glyphicon-remove" style="cursor: pointer;"></i>
								</div>
							</c:forEach>
						</c:otherwise>
					</c:choose>
	
				</div>
			</div> 
			
			
			<!-- 日期显示结束 add by zwy -->
			

			<div class="form-group" >

				<label class="col-sm-3 control-label no-padding-right">用户CPU限额</label>

				<div class="col-xs-12 col-sm-9">

					<div class="clearfix help-validate">

						<input class="cpuLimit" value="${user.cpuLimit}" name="cpuLimit" type="text">

						<span>Core</span>

					</div>

				</div>

			</div>

			

			<div class="form-group" >

				<label class="col-sm-3 control-label no-padding-right">用户内存限额</label>

				<div class="col-xs-12 col-sm-9">

					<div class="clearfix help-validate">

						<input class="memLimit" value="${user.memLimit}" name="memLimit" type="text" >

						<span>MB</span>

					</div>

				</div>

			</div>

			

			<div class="form-group" >

				<label class="col-sm-3 control-label no-padding-right">用户带宽限额</label>

				<div class="col-xs-12 col-sm-9">

					<div class="clearfix help-validate">

						<input class="bandwidthLimit" name="bandwidthLimit" value="${user.bandwidthLimit}" type="text">

						<span>Mbps</span>

					</div>

				</div>

			</div>

			

			<input id="_ips" type="hidden" name="ips" value="" type="text">
			<input id="_dateTimes" type="hidden" name="dateTimes" value="" type="text">
			<input id="_times" type="hidden" name="times" value="" type="text">
			
			<div class="clearfix form-actions">
				<div class="col-md-offset-3 col-md-9">
					<button id="_submit" type="button" class="btn btn-info" data-loading-text="正在提交...">
						<i class="ace-icon fa fa-check bigger-110"></i>
						提交
					</button>

					&nbsp; &nbsp; &nbsp;
					<button id="_cancle" class="btn" type="reset">
						<i class="ace-icon fa  fa-times bigger-110"></i>
						取消
					</button>
				</div>
			</div>
		</form>

	</div>
</div>

<script type="text/javascript">
	$('.page-content-area').ace_ajax('loadScripts', scripts, function() {
		jQuery(function($) {
			console.log($("#_password").val());
			
			//焦点
			$("#_account").focus();
			
			//帮助查看
			$('[data-rel=tooltip]').tooltip({container:'body'});
			
			// add by zwy
			//添加ip区间按钮
			
			$(document).off('click','.ipRow .glyphicon-plus').on('click','.ipRow .glyphicon-plus',function(){
				var htmlAdd="<div class='clearfix help-validate ipRange' style='margin-top:6px;''>"+
				"<input class='ip startIp' value='' type='text'> <span>-</span> <input class='ip endIp' value='' type='text'>"+
				" <i class='ace-icon glyphicon glyphicon-remove' style='cursor: pointer;'></i></div>";
				$(".ipRangeRow").append(htmlAdd);
				$('.ipRow .glyphicon-remove').click(function(){
					$(this).parent().remove();
				}); 
				
			});
			
			//比较ip地址大小，正确返回-1
			function compareIP(ipBegin,ipEnd){
				var temp1;
				var temp2;
				temp1=ipBegin.split(".");
				temp2=ipEnd.split(".");
				for(var i=0;i<4;i++){
					if(parseInt(temp1[i])>parseInt(temp2[i])){
						return 1;
					}else if(parseInt(temp1[i])<parseInt(temp2[i])){
						return -1;
					}
				}
				return 0;
			}
			
			//判断ip区间
			$(document).off('blur','.ipRange').on('blur','.ipRange',function(){
				var reg=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/;
				var startIp=$(this).find(".startIp").val();
				var endIp=$(this).find(".endIp").val();
				//提示错误的情况：在没有错误提示框的情况下有一项为空，有一项不空且出错（允许结束项为空），两项不为空且不出错且范围不对，
				if(
				   (startIp==""&&endIp!=="")
				   ||(startIp!==""&&!reg.test(startIp))||(endIp!==""&&!reg.test(endIp))
				   ||(startIp!==""&&endIp!==""&&reg.test(endIp)&&reg.test(startIp)&&compareIP(startIp,endIp)!==-1)
				   ){
					if($(this).find(".help-block-ip").length==0){
						$(this).append("<div class='help-block-ip' style='color:#d16e6c'>请输入正确的ip地址范围</div>");
						//$(this).parent().parent().removeClass('has-info').addClass('has-error');
					}
				}else if(
						(startIp==""&&endIp=="")||(startIp!==""&&endIp!==""&&reg.test(endIp)&&reg.test(startIp)&&compareIP(startIp,endIp)==-1)
						||(startIp!==""&&reg.test(startIp)&&endIp=="")
						){//去掉错误框的情况：两项都为空，两项都不为空且两项都对且范围对（允许结束项为空）
					//$(this).parent().parent().removeClass('has-error');
					$(this).find('.help-block-ip').remove();
				}
			});
			
			//添加日期时间按钮
			$(document).off('click','.dateRangeRow .glyphicon-plus').on('click','.dateRangeRow .glyphicon-plus',function(){
				var htmlAdd="<div class='clearfix help-validate dateRange' style='margin-top:6px;'>"+
				"<input class='form-data date-timepicker date-timepicker1'  type='text' value='<fmt:formatDate value='${item.startDatetime}' pattern='yyyy-MM-dd HH:mm' />'/>"+
				" <span>-</span> <input class='form-data date-timepicker date-timepicker2' value='<fmt:formatDate value='${item.endDatetime}' pattern='yyyy-MM-dd HH:mm' />' type='text'/>"+
				" <i class='ace-icon glyphicon glyphicon-remove' style='cursor: pointer;'></i></div>";
				$(".dateRangeRow").append(htmlAdd);
				$('.date-timepicker').datetimepicker({
					 format: 'YYYY-MM-DD HH:mm',//use this option to display seconds
					 icons: {
						time: 'fa fa-clock-o',
						date: 'fa fa-calendar',
						up: 'fa fa-chevron-up',
						down: 'fa fa-chevron-down',
						previous: 'fa fa-chevron-left',
						next: 'fa fa-chevron-right',
						today: 'fa fa-arrows ',
						clear: 'fa fa-trash',
						close: 'fa fa-times'
					 }
				}).next().on(ace.click_event, function(){
						$(this).prev().focus();
				});

				
				$('.dateRangeRow .glyphicon-remove').click(function(){
					$(this).parent().remove();
					$(document).find(".bootstrap-datetimepicker-widget").css("display","none");
				}); 
			});
			
			//判断date区间
			$(document).off('blur','.dateRange').on('blur','.dateRange',function(){
				var DateStr1=$(this).find(".date-timepicker1").val();
				var DateStr2=$(this).find(".date-timepicker2").val();
				var startTime=DateStr1+":00";
				var endTime=DateStr2+":00";
				var date1=new Date(Date.parse(startTime.replace("-/g","/")));
				var date2=new Date(Date.parse(endTime.replace("-/g","/")));
				//提示错误的情况：在没有错误提示框的情况下有一项为空且另一项不为空，两项不为空且范围不对，
				if(
				   (DateStr1==""&&DateStr2!=="")||(DateStr1!==""&&DateStr2=="")
				   ||(DateStr1!==""&&DateStr1!==""&&date1>=date2)
				   ){
					if($(this).find(".help-block-date").length==0){
						$(this).append("<div class='help-block-date' style='color:#d16e6c'>请输入正确的时间范围</div>");
					}
				}else if(
						(DateStr1==""&&DateStr2=="")||(DateStr1!==""&&DateStr2!==""&&date1<date2)
						){//去掉错误框的情况：两项都为空，两项都不为空且范围对
					$(this).find('.help-block-date').remove();
				}
			});
			
			//添加循环时间按钮
			$(document).off('click','.everydayRow .glyphicon-plus').on('click','.everydayRow .glyphicon-plus',function(){
				var htmlAdd="<div class='clearfix help-validate everydayRange' style='margin-top:6px;'>"+
				"<input class='form-data timepicker timepicker1' value='' type='text'/> <span>- </span>"+
				"<input class='form-data timepicker timepicker2' value='' type='text'/>"+
				" <i class='ace-icon glyphicon glyphicon-remove' style='cursor: pointer;'></i></div>";
				$(".everydayRow").append(htmlAdd);
				$('.everydayRange .glyphicon-remove').click(function(){
					$(this).parent().remove();
				}); 
			});
			
			//比较时分,正确返回-1
			function compareHM(t1,t2){
				var temp1=t1.split(":");
				var temp2=t2.split(":");
				for(var i=0;i<2;i++){
					if(parseInt(temp1[i])>parseInt(temp2[i])){
						return 1;
					}else if(parseInt(temp1[i])<parseInt(temp2[i])){
						return -1;
					}
				}
				return 0;
			}
			
			//判断循环时间范围
			$(document).off('blur','.everydayRange').on('blur','.everydayRange',function(){
				var reg=/^([01]\d|2[01234]):([0-5]\d|60)$/;
				var startTimep=$(this).find(".timepicker1").val();
				var endTimep=$(this).find(".timepicker2").val();
				//提示错误的情况：在没有错误提示框的情况下有一项为空，有一项不空且出错，两项不为空且不出错且范围不对，
				if(
				   (startTimep==""&&endTimep!=="")||(startTimep!==""&&endTimep=="")
				   ||(startTimep!==""&&!reg.test(startTimep))||(endTimep!==""&&!reg.test(endTimep))
				   ||(startTimep!==""&&endTimep!==""&&reg.test(endTimep)&&reg.test(startTimep)&&compareHM(startTimep,endTimep)!==-1)
				   ){
					if($(this).find(".help-block-timepicker").length==0){
						$(this).append("<div class='help-block-timepicker' style='color:#d16e6c'>请输入正确的时间地址范围，时间格式为xx:xx</div>");
					}
				}else if(
						(startTimep==""&&endTimep=="")||(startTimep!==""&&endTimep!==""&&reg.test(endTimep)&&reg.test(startTimep)&&compareHM(startTimep,endTimep)==-1)
						){//去掉错误框的情况：两项都为空，两项都不为空且两项都对且范围对
					$(this).find('.help-block-timepicker').remove();
				}
			});
			
			
			 //日期	
			$('.date-timepicker').datetimepicker({
				 format: 'YYYY-MM-DD HH:mm',//use this option to display seconds
				 icons: {
					time: 'fa fa-clock-o',
					date: 'fa fa-calendar',
					up: 'fa fa-chevron-up',
					down: 'fa fa-chevron-down',
					previous: 'fa fa-chevron-left',
					next: 'fa fa-chevron-right',
					today: 'fa fa-arrows ',
					clear: 'fa fa-trash',
					close: 'fa fa-times'
				 }
			}).next().on(ace.click_event, function(){
					$(this).prev().focus();
			});
			
			
			// 提交
			$("#_submit").click(function(){
				
				
				//判断是否选中某个角色
				var isRole=false;
				$("input[name='roleId']:checked").each(function(i, d){	
						isRole=true;
				
				});
				//console.log(isRole);
				if(!isRole && $('.form-group-role').find(".help-block-ip").length==0){
					$('.form-group-role').append("<div class='help-block-ip' style='color:#d16e6c'>此项为必选项</div>");
					$('.form-group-role .control-label').css("color","#d16e6c");
				} else if(isRole){
					$('.form-group-role').find('.help-block-ip').remove();
					$('.form-group-role .control-label').css("color","#393939");
				}
				
				if($('.form-group-role').find('.help-block-ip').length>0||$('.form-group-time').find('.help-block-date').length>0||$(".ipRange").find(".help-block-ip").length>0){
					return false;
				}
				
				
				//console.log($('#_editForm').validate());
				if($('#_editForm').validate()){
					var roleIds = "";//代表角色
					$("input[name='roleId']:checked").each(function(i, d){
						if(i > 0){
							roleIds += ",";
						}
						roleIds += $(this).val();
					});
					$("#_roleIds").val(roleIds);
					
					//获取选择的多个ip时间段
					var ipRowLen=$("#_editForm").find(".ipRange").length;
					var totalIp=[];//代表多个ip段
					var ipRow="";
					var startIp="";
					var endIp="";
					for(var i=0;i<ipRowLen;i++){
						startIp=$("#_editForm").find(".ipRange").find(".startIp").eq(i).val();
						endIp=$("#_editForm").find(".ipRange").find(".endIp").eq(i).val();
						ipRow=startIp+'-'+endIp;
						totalIp.push(ipRow);
					}
					$("#_ips").val(totalIp);
					
					//获取选择的多个日期时间段
					var dateRowLen=$("#_editForm").find(".dateRange").length;
					var totaldate=[];//代表多个日期段
					var dateRow="";
					var startDate="";
					var endDate="";
					for(var i=0;i<dateRowLen;i++){
						startDate=$("#_editForm").find(".dateRange").find(".date-timepicker1").eq(i).val();
						endDate=$("#_editForm").find(".dateRange").find(".date-timepicker2").eq(i).val();
						dateRow=startDate+'#'+endDate;
						totaldate.push(dateRow);
					}
					$("#_dateTimes").val(totaldate);
					
					//获取选择的多个每天循环时间段
					var timeRowLen=$("#_editForm").find(".everydayRange").length;
					var totaltime=[];//代表多个时间段
					var timeRow="";
					var startTime="";
					var endTime="";
					for(var i=0;i<timeRowLen;i++){
						startTime=$("#_editForm").find(".everydayRange").find(".timepicker1").eq(i).val();
						endTime=$("#_editForm").find(".everydayRange").find(".timepicker2").eq(i).val();
						timeRow=startTime+'-'+endTime;
						totaltime.push(timeRow);
					}
					$("#_times").val(totaltime);
					
					var btn = $(this);
					btn.button('loading');
					//console.log($.formJson('_editForm'));
					console.log($.formJson('_editForm').ips);
					console.log($.formJson('_editForm').dateTimes);
					console.log($.formJson('_editForm').times);
					//Object { id: "12", account: "admin5", password: "", roleIds: "", isEnable: "true", : Array[8], ips: "1-3,3-5", date-range-picker: "07/04/2018 - 07/13/2018" }
					$.post("${_path}/admin/user/save", $.formJson('_editForm'),function(d) {
						if(d){
							btn.button('reset');
							if(d.code == 1){
								$.aceRedirect("${_path}/admin/user");
							}
							else {
								$.gritter.add({text: d.message});
							}
						}
			        },'json');
				}
			});
			
			// 取消
			$("#_cancle").click(function(){
				$.aceRedirect("${_path}/admin/user");
			});
			
			// 回车绑定
			$(".form-data").bind('keypress',function(event){
                if(event.keyCode == "13"){
                	event.preventDefault();
                	$("#_submit").click();
                }
            });
			
		});
	});
</script>
